#include "mainwindow.h"
#include "ui_mainwindow.h"


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 播放器类
    player = new QMediaPlayer(this);

    // 自动初始化
    INTO();
    ui->Slider1->setRange(0, player->duration() / 1000); // duration 返回毫秒，这里转换为秒
    ui->Slider1->setTickPosition(QSlider::TicksBelow);
    ui->Slider1->setTickInterval(10);

    // 设置结束时间
    connect(player, &QMediaPlayer::durationChanged, this, [this]() {
        int MusicTime = player->duration() / 1000;
        ui->Slider1->setRange(0, MusicTime);
            EndS1 = MusicTime / 60;
            EndS2 = MusicTime % 60;
            if(EndS2 < 10)
            {
                EndSum = "0" + QString::number(EndS1) + ":0" + QString::number(EndS2);
            }
            else
            {
                EndSum = "0" + QString::number(EndS1) + ":" + QString::number(EndS2);
            }

            ui->end->setText(EndSum);
            });

    // 设置播放到哪里的时间
    connect(player, &QMediaPlayer::positionChanged, this, [this](qint64 position) {
                int MusicTime = position / 1000;
                ui->Slider1->setValue(MusicTime); // 转换为秒
                StartS1 = MusicTime / 60;
                StartS2 = MusicTime % 60;
                if(StartS2 < 10)
                {
                    StartSum = "0" + QString::number(StartS1) + ":0" + QString::number(StartS2);
                }
                else
                {
                    StartSum = "0" + QString::number(StartS1) + ":" + QString::number(StartS2);
                }

                ui->Start->setText(StartSum);

            });


    // 自动下一曲
    connect(player, &QMediaPlayer::mediaStatusChanged, this, [this](QMediaPlayer::MediaStatus status){
        if(status == QMediaPlayer::EndOfMedia)
        {
            ui->Next->click();
        }
    });

    // 绑定触发回车键 （QlineEdit）
    connect(ui->search1, &QLineEdit::returnPressed, this, [this](){
       ui->search2->click();
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}


// 函数作用: 初始化整个ui界面和导入歌单
void MainWindow::INTO()
{
    // 自动初始化歌单:
    {
        QString fileName = QDir::currentPath() + "/mp3";
        QDir dir(fileName);


        // 获取MP3文件
        QStringList nameFilters;
        nameFilters << "*.mp3";

        // 将mp3文件全部导入MusicList中
        QStringList files = dir.entryList(nameFilters, QDir::Files | QDir::Readable, QDir::Name);
        ui->MusicList->addItems(files);

        playPath = fileName;
    }

    // 防冲突闪退
    ui->play->setEnabled(false);
    ui->Prev->setEnabled(false);
    ui->Next->setEnabled(false);


    // 因为直接取消会导致箭头颜色变灰色，影响观感，所以直接拿一个透明wight覆盖在上面，达到禁用效果
    // ui->Slider1->setEnabled(false);

    ui->Start->setAlignment(Qt::AlignCenter);
    ui->Start->setReadOnly(true);
    ui->end->setAlignment(Qt::AlignCenter);
    ui->end->setReadOnly(true);



    ui->volume->setAlignment(Qt::AlignCenter);
    ui->volume->setReadOnly(true);

    ui->current->setAlignment(Qt::AlignCenter);
    ui->current->setReadOnly(true);
}

// 播放和暂停音乐
void MainWindow::on_play_clicked()
{
    if(player->state() == QMediaPlayer::PlayingState)
    {
        player->pause();
        ui->play->setText("Play");
    }
    else
    {
        player->play();
        ui->play->setText("Pause");
    }
}

// 设置音量
void MainWindow::on_Slider2_sliderMoved(int position)
{
    player->setVolume(position);
    ui->volume->setText(QString::number(position));
}

// 更改歌单
void MainWindow::on_AddMusic_clicked()
{
    // 获取文件夹路径，构造dir(用于访问和操作文件系统目录)
    QString fileName = QFileDialog::getExistingDirectory(NULL,"Select Music Dir",".",NULL);
    if(fileName != nullptr)
    {
        QDir dir(fileName); // 根据路径构造文件夹


        // 获取MP3文件
        QStringList nameFilters;
        nameFilters << "*.mp3"; // 过滤器

        // 将mp3文件全部导入MusicList中
        QStringList files = dir.entryList(nameFilters, QDir::Files | QDir::Readable, QDir::Name);
        ui->MusicList->addItems(files);

        playPath = fileName;
    }

}

// 函数功能: 双击歌曲可以直接播放
void MainWindow::on_MusicList_itemDoubleClicked(QListWidgetItem *item)
{
    // 防冲突闪退
    ui->play->setEnabled(true);
    ui->Prev->setEnabled(true);
    ui->Next->setEnabled(true);

    PlayRow = ui->MusicList->row(item);
    player->stop();
    player->setMedia(QUrl::fromLocalFile(playPath+"/"+item->text()));
    player->play();

    //ui->Slider1->setValue(player->position());

    // 显示正在播放的歌曲的歌曲名
    ui->current->setText(item->text());

    ui->play->setText("Pause");
}

// 上一曲
void MainWindow::on_Prev_clicked()
{
    if(PlayRow == 0){
        PlayRow = ui->MusicList->count() - 1;
    }
    else{
        PlayRow--;
    }
    QListWidgetItem *item = ui->MusicList->item(PlayRow);
    item->setSelected(true);
    player->stop();
    player->setMedia(QUrl::fromLocalFile(playPath+"/"+item->text()));
    player->play();
    ui->current->setText(item->text()); // current 当前播放的是哪一首歌
}

// 下一曲
void MainWindow::on_Next_clicked()
{
    if(PlayRow + 1 == ui->MusicList->count()){
        PlayRow = 0;
    }
    else{
        PlayRow++;
    }
    QListWidgetItem *item = ui->MusicList->item(PlayRow);
    item->setSelected(true);
    player->stop();
    player->setMedia(QUrl::fromLocalFile(playPath+"/"+item->text()));
    player->play();
    ui->current->setText(item->text());
}

// 快进15s
void MainWindow::on_forward_clicked()
{
    player->setPosition(player->position() + 15000);
}

// 回退15s
void MainWindow::on_back_clicked()
{
    player->setPosition(player->position() - 15000);
}

// 处理搜索
void MainWindow::on_search2_clicked()
{
    if(ui->search1->text() == "")
    {
        {
            ui->MusicList->clear();

            QDir dir(playPath);

            // 获取MP3文件
            QStringList nameFilters;
            nameFilters << "*.mp3";

            // 将mp3文件全部导入MusicList中
            QStringList files = dir.entryList(nameFilters, QDir::Files | QDir::Readable, QDir::Name);
            ui->MusicList->addItems(files);
        }
    }
    else
    {
        ui->MusicList->clear();
        QString name = ui->search1->text();
        QDir dir(playPath);


        // 获取MP3文件
        QStringList nameFilters;
        nameFilters << "*" + name + "*";

        // 将mp3文件全部导入MusicList中
        QStringList files = dir.entryList(nameFilters, QDir::Files | QDir::Readable, QDir::Name);
        ui->MusicList->addItems(files);
    }

}
